<?php
/**
 * Zip
 *
 * Extremely fast and easy to use zip file builder. Created to add on-the-fly
 * zip compressed file streaming.
 *
 * @author  Badrus Said <badrus.said@gmail.com>
 * @protected
 * @singleton
 */
final class api_Zip {
    private $a = array(), $b = array(), $e = 0, $x = null, $z = null;
    public function __construct() {
        $this->x = pack("vvvv", 0, 0, 0, 0);
        $this->z = pack("VVV", 0, 0, 0);
    }
    public function addPath($n) {
        $n = strtr($n, "\\", "/");
        $l = strlen($n);
        $m = "\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
        $this->a[] = "\x50\x4b\x03\x04".$m.$this->z.pack("vv", $l, 0).$n.$this->z;
        $this->b[] = "\x50\x4b\x01\x02\x00\x00".$m.$this->z.pack("v", $l).$this->x.pack("VV", 16, $this->e).$n;
        $this->e = strlen(implode("", $this->a));
    }
    public function addFile($n, $f) {
        $x = file_get_contents($f);
        $n = strtr($n, "\\", "/");
        $l = strlen($n);
        $z = gzcompress($x);
        $f = substr(substr($z, 0, strlen($z) - 4), 2);
        $t = pack("VVV", crc32($x), strlen($f), strlen($x));
        $u = "\x14\x00\x00\x00\x08\x00\x00\x00\x00\x00";
        $this->a[] = "\x50\x4b\x03\x04".$u.$t.pack("vv", $l, 0).$n.$f.$t;
        $this->b[] = "\x50\x4b\x01\x02\x00\x00".$u.$t.pack("v", $l).$this->x.pack("VV", 32, $this->e).$n;
        $this->e = strlen(implode("", $this->a));
    }
    public function getFile() {
        $x = implode("", $this->a);
        $b = implode("", $this->b);
        $c = sizeof($this->b);
        return $x.$b."\x50\x4b\x05\x06\x00\x00\x00\x00".pack("vvVV", $c, $c, strlen($b), strlen($x))."\x00\x00";
    }
    public function save($n) {
        file_put_contents($n, $this->getFile());
    }
    public function sendFile($n) {
        if (ini_get("zlib.output_compression")) ini_set("zlib.output_compression", "Off");
        $x = $this->getFile();
        $i = array(
            "Pragma: public",
            "Expires: 0",
            "Cache-Control: must-revalidate,post-check=0,pre-check=0",
            "Content-Type: application/zip",
            "Content-Disposition: attachment;filename={$n}.zip;",
            "Content-Transfer-Encoding: binary",
            "Content-Length: ".strlen($x)
        );
        foreach($i as $j) header($j);
        file_put_contents("php://output", $x);
        exit;
    }
}
?>